package com.ambimmort.ucagent.modules.AAAReader;

import com.ambimmort.ucagent.appframework.Module;
import com.ambimmort.ucagent.modules.server.codec.UcRawMessage;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;

/**
 * Created by hedingwei on 2015/1/22.
 */
public class AAAReader extends Module implements Runnable {

    ServerSocket server = null;

    public AAAReader() {
        try {
            server = new ServerSocket(9999);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getName() {
        return "AAAReader";
    }

    @Override
    protected void prestart() throws Throwable {


    }

    @Override
    protected void poststart() throws Throwable {
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            byte[] receiveData = new byte[5000];
            DatagramSocket serverSocket = new DatagramSocket(5050);
            int count = 0;
            int successCount = 0;
            UcRawMessage msg = null;
            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                count++;
                byte[] data = receivePacket.getData();
                System.out.println("RECEIVED: " + new String(data));
                try{
//                    A3Pub p = new A3Pub(data);
//                    msg = p.process();
//                    successCount++;
                }catch(Exception e){
                    e.printStackTrace();
                }
                System.out.println("count:"+count+"\t successCount:"+successCount);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
